package view;

import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.StageStyle;
import model.bean.Message;
import model.client.Client;
import model.dao.Database;
import model.utils.StringWidthAndHeightUtil;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 用户登录后界面，用户处于在线状态
 */
public class OnLineView extends Window{

    private int id;

    private Database database;

    private boolean flag = true;

    private String headPortrait = null;

    private String your_nickname = null;

    private String your_account = null;

    private Client client;

    private Vector<MsgListItemView> fListItemViews;
    private Vector<MsgListItemView> gListItemViews;

    private Map<String, Vector<ChatListItemView>> fMsgListItemMap;
    private Map<String, Vector<ChatListItemView>> gMsgListItemMap;
    private Map<String, Vector<GMItemView>> groupMemberMap;

    private ListView fListView;
    private ListView gListView;

    private ListView fMsgListView;
    private ListView gMsgListView;
    private ListView groupMemberListView;

    public OnLineView(int id) throws Exception {
        root = FXMLLoader.load(getClass().getClassLoader().getResource("onLine.fxml"));
        Scene scene = new Scene(root, 1050, 600);
        scene.setFill(Color.TRANSPARENT);
        setScene(scene);
        initStyle(StageStyle.TRANSPARENT);
        setResizable(false);
        setTitle("OnLine");

        this.id = id;

        init();
        move();
        quit();
        minimize();

    }

    private void init() throws Exception {

        client = new Client(this);

        database = new Database();
        database.connect();

        ((Button)findViewById("add")).setFocusTraversable(false);
        ((Button)findViewById("friends")).requestFocus();

        ResultSet resultSet = database.execResult("select account, nickname, portrait from user where user_id = ?", String.valueOf(id));
        while (resultSet.next()) {
            your_account = resultSet.getString("account");
            your_nickname = resultSet.getString("nickname");
            headPortrait = resultSet.getString("portrait");
        }
        resultSet.close();

        ((ImageView)findViewById("headImg")).setStyle("-fx-image: url(" + headPortrait + ");");

        fListView = (ListView) findViewById("fList");
        gListView = (ListView) findViewById("gList");
        fMsgListView = (ListView) findViewById("fMsgList");
        gMsgListView = (ListView) findViewById("gMsgList");
        groupMemberListView = (ListView) findViewById("gMemList");
        fListItemViews = new Vector<>();
        gListItemViews = new Vector<>();

        fMsgListItemMap = new HashMap<>();
        gMsgListItemMap = new HashMap<>();
        groupMemberMap = new HashMap<>();

        fListView.setFocusTraversable(false);
        fListView.setVisible(true);
        gListView.setFocusTraversable(false);
        gListView.setVisible(false);

        addFriends();
        addGroups();
    }



    @Override
    public void quit() {
        ((Button)findViewById("quit")).setTooltip(new Tooltip("退出"));
        ((Button)findViewById("quit")).setOnAction(event -> {
            flag = false;
            String sql = "delete from online where your_id = ?";
            try {
                database.exec(sql, String.valueOf(id));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            close();
            System.exit(0);
        });
    }

    @Override
    public void minimize() {
        ((Button)findViewById("min")).setTooltip(new Tooltip("最小化"));
        ((Button)findViewById("min")).setOnAction(event -> {
            setIconified(true);
        });
    }

    /**
     * 给两个ListView添加数据
     * @throws IOException
     */
    private void addFriends() throws Exception {
        String sql = "select friend_account from friends where your_id = ? and del = 0";
        ResultSet resultSet = database.execResult(sql, String.valueOf(id));
        List<String> friends = new ArrayList<>();
        while (resultSet.next()) {
            friends.add(resultSet.getString("friend_account"));
        }
        resultSet.close();
        for (String friend : friends) {
            String s = "select user_id, nickname, portrait from user where account = ?";
            ResultSet resultSet1 = database.execResult(s, friend);
            String nickname = null;
            String img = null;
            int user_id = -1;
            while (resultSet1.next()) {
                user_id = resultSet1.getInt("user_id");
                nickname = resultSet1.getString("nickname");
                img = resultSet1.getString("portrait");
                System.out.println(nickname);
                System.out.println(img);
            }
            resultSet1.close();
            if (nickname != null) {
                MsgListItemView itemView = new MsgListItemView(nickname, "", MsgListItemView.TYPE_FRIENDS);
                itemView.setHeadPortrait(img);
                int finalUser_id = user_id;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ResultSet res = null;
                        try {
                            while (true) {
                                res = database.execResult("select online_id from online where your_id = ?", String.valueOf(finalUser_id));
                                boolean f;
                                if (res.next()) {
                                    f = true;
                                } else {
                                    f = false;
                                }
                                boolean finalFlag = f;
                                Platform.runLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (finalFlag) {
                                            itemView.setOnlineState(1);
                                        } else {
                                            itemView.setOnlineState(0);
                                        }
                                    }
                                });
                                Thread.sleep(10*1000);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                fListItemViews.add(itemView);
                fListView.getItems().add(fListItemViews.get(fListItemViews.size()-1).getPane());
                Vector<ChatListItemView> vector = new Vector<>();
                fMsgListItemMap.put(nickname, vector);
            }
        }
    }

    private void addGroups() throws Exception {

        String sql = "select group_id from group_members where user_id = ?";
        ResultSet resultSet = database.execResult(sql, String.valueOf(id));
        List<String> groups = new ArrayList<>();
        while (resultSet.next()) {
            groups.add(resultSet.getString("group_id"));
        }
        resultSet.close();
        for (String group : groups) {
            String sql2 = "select user_id from group_members where group_id = ?";
            ResultSet resultSet1 = database.execResult(sql2, group);
            List<String> groupMembersId = new ArrayList<>();
            while (resultSet1.next()) {
                groupMembersId.add(resultSet1.getString("user_id"));
            }
            resultSet1.close();
            Vector<GMItemView> views = new Vector<>();
            for (String memberId : groupMembersId) {
                String sql4 = "select nickname, portrait from `user` where user_id = ?";
                ResultSet resultSet4 = database.execResult(sql4, memberId);
                String memberName = null;
                String memberPortrait = null;
                if (resultSet4.next()) {
                    memberName = resultSet4.getString("nickname");
                    memberPortrait = resultSet4.getString("portrait");
                }
                if (!memberName.isEmpty()) {
                    GMItemView view = new GMItemView(memberName, memberPortrait);
                    views.add(view);
                }
            }
            String sql3 = "select group_name, group_portrait from `group` where group_id = ?";
            ResultSet resultSet2 = database.execResult(sql3, group);
            String group_name = null;
            String group_portrait = null;
            if (resultSet2.next()) {
                group_name = resultSet2.getString("group_name");
                group_portrait = resultSet2.getString("group_portrait");
                System.out.println(group_name + "---" + group_portrait);
            }
            if (!group_name.isEmpty()) {
                MsgListItemView itemView = new MsgListItemView(group_name, "", MsgListItemView.TYPE_GROUP);
                itemView.setHeadPortrait(group_portrait);
                itemView.setOnlineState(1);
                gListItemViews.add(itemView);
                gListView.getItems().add(gListItemViews.get(gListItemViews.size()-1).getPane());

                Vector<ChatListItemView> vector = new Vector<>();
                gMsgListItemMap.put(group_name, vector);

                groupMemberMap.put(group_name, views);
            }
        }
    }

    public void onloadMsg(String nickname) {
        fMsgListView.getItems().clear();
        Vector<ChatListItemView> vector = fMsgListItemMap.get(nickname);
        for (int i=0; i<vector.size(); i++) {
            fMsgListView.getItems().add(vector.get(i).getPane());
        }
    }

    public void onloadGroupMsg(String group_name) {
        gMsgListView.getItems().clear();
        Vector<ChatListItemView> vector = gMsgListItemMap.get(group_name);
        for (int i=0; i<vector.size(); i++) {
            gMsgListView.getItems().add(vector.get(i).getPane());
        }
    }

    public void onloadGroupMember(String group_name) {
        groupMemberListView.getItems().clear();
        Vector<GMItemView> vector = groupMemberMap.get(group_name);
        for (int i=0; i<vector.size(); i++) {
            groupMemberListView.getItems().add(vector.get(i).getPane());
        }
    }

    public void sendMsgToFriend(String name, String msg, String friendNickname) throws IOException {
        ChatListItemView view = new ChatListItemView(810, 100);
        view.setName(name, ChatListItemView.DIRECTION_RIGHT);
        view.setMsg(msg, ChatListItemView.DIRECTION_RIGHT);
        view.setPortrait(headPortrait, ChatListItemView.DIRECTION_RIGHT);
        view.setMsgLabelSize(StringWidthAndHeightUtil.getWidth(msg, 750), StringWidthAndHeightUtil.getHeight(msg, 750), ChatListItemView.DIRECTION_RIGHT);
        fMsgListItemMap.get(friendNickname).add(view);

        fMsgListView.getItems().add(fMsgListItemMap.get(friendNickname).get(fMsgListItemMap.get(friendNickname).size() - 1).getPane());
    }

    public void receiveMsgFromFriend(String name, String msg, String friendNickname, String portrait) throws IOException {
        ChatListItemView view = new ChatListItemView(810, 100);
        view.setName(name, ChatListItemView.DIRECTION_LEFT);
        view.setMsg(msg, ChatListItemView.DIRECTION_LEFT);
        view.setPortrait(portrait, ChatListItemView.DIRECTION_LEFT);
        view.setMsgLabelSize(StringWidthAndHeightUtil.getWidth(msg, 750), StringWidthAndHeightUtil.getHeight(msg, 750), ChatListItemView.DIRECTION_LEFT);

        fMsgListItemMap.get(friendNickname).add(view);
        fMsgListView.getItems().add(fMsgListItemMap.get(friendNickname).get(fMsgListItemMap.get(friendNickname).size() - 1).getPane());
    }

    public void sendMsgToGroup(String name, String msg, String groupName) throws IOException {
        ChatListItemView view = new ChatListItemView(660, 100);
        view.setName(name, ChatListItemView.DIRECTION_RIGHT);
        view.setMsg(msg, ChatListItemView.DIRECTION_RIGHT);
        view.setPortrait(headPortrait, ChatListItemView.DIRECTION_RIGHT);
        view.setMsgLabelSize(StringWidthAndHeightUtil.getWidth(msg, 600), StringWidthAndHeightUtil.getHeight(msg, 600), ChatListItemView.DIRECTION_RIGHT);
        System.out.println("sendMsgToGroup----" + groupName);
        gMsgListItemMap.get(groupName).add(view);
        gMsgListView.getItems().add(gMsgListItemMap.get(groupName).get(gMsgListItemMap.get(groupName).size() - 1).getPane());
    }

    public void receiveMsgFromGroup(String name, String msg, String group_name, String portrait) throws IOException {
        ChatListItemView view = new ChatListItemView(660, 100);
        view.setName(name, ChatListItemView.DIRECTION_LEFT);
        view.setMsg(msg, ChatListItemView.DIRECTION_LEFT);
        view.setPortrait(portrait, ChatListItemView.DIRECTION_LEFT);
        view.setMsgLabelSize(StringWidthAndHeightUtil.getWidth(msg, 600), StringWidthAndHeightUtil.getHeight(msg, 600), ChatListItemView.DIRECTION_LEFT);

        gMsgListItemMap.get(group_name).add(view);
        gMsgListView.getItems().add(gMsgListItemMap.get(group_name).get(gMsgListItemMap.get(group_name).size() - 1).getPane());
    }

    public void addNewFriend(String friend_account) {
        System.out.println("加好友");

        String check = "select friends_id, del from `friends` where your_id = ? and friend_account = ?";
        int friends_id = -1;
        int del = -1;
        try {
            ResultSet result = database.execResult(check, String.valueOf(id), friend_account);
            if (result.next()) {
                friends_id = result.getInt("friends_id");
                del = result.getInt("del");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (friends_id != -1 && del == 0) {
            try {
                new PBoxView(friend_account + "已经是您的好友， 请勿重复加好友！").show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            String sql = "insert into friends(your_id, friend_account) values(?, ?)";
            try {
                database.exec(sql, String.valueOf(id), friend_account);
                new PBoxView("操作成功！").show();
            } catch (Exception e) {
                e.printStackTrace();
            }

            String sql2 = "select user_id, nickname, portrait from user where account = ?";
            int user_id = -1;
            String nickname = null;
            String img = null;

            try {
                ResultSet set = database.execResult(sql2, friend_account);
                if (set.next()) {
                    user_id = set.getInt("user_id");
                    nickname = set.getString("nickname");
                    img = set.getString("portrait");
                }
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (user_id != -1) {
                String sql3 = "select online_id from online where your_id = ?";
                int online_id = -1;
                try {
                    database.exec(sql, String.valueOf(user_id), your_account);
                    ResultSet resultSet2 = database.execResult(sql3, String.valueOf(user_id));
                    if (resultSet2.next()) {
                        online_id = resultSet2.getInt("online_id");
                    }
                    resultSet2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                MsgListItemView itemView = null;
                try {
                    itemView = new MsgListItemView(nickname, "", MsgListItemView.TYPE_FRIENDS);
                    itemView.setHeadPortrait(img);
                    if (online_id != -1) {
                        itemView.setOnlineState(1);
                    } else {
                        itemView.setOnlineState(0);
                    }
                    fListItemViews.add(itemView);
                    fListView.getItems().add(fListItemViews.get(fListItemViews.size()-1).getPane());
                    Vector<ChatListItemView> vector = new Vector<>();
                    fMsgListItemMap.put(nickname, vector);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

    }

    public void addNewGroup(int groupId) {
        System.out.println("加群");
        String check = "select user_id from `group_members` where group_id = ?";
        boolean isMember = false;

        List<String> uids = new ArrayList<>();
        try {
            ResultSet resultSet = database.execResult(check, String.valueOf(groupId));
            while (resultSet.next()) {
                int uid = resultSet.getInt("user_id");
                uids.add(String.valueOf(uid));
                if (uid == id) {
                    isMember = true;
                    new PBoxView("您已经是该群成员，请勿重复加入！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        uids.add(String.valueOf(id));
        if (!isMember) {
            String sql = "insert into `group_members`(group_id, user_id) values(?, ?)";
            try {
                database.exec(sql, String.valueOf(groupId), String.valueOf(id));
                new PBoxView("操作成功！").show();

                String sql3 = "select group_name, group_portrait from `group` where group_id = ?";
                ResultSet resultSet2 = database.execResult(sql3, String.valueOf(groupId));
                String group_name = null;
                String group_portrait = null;
                if (resultSet2.next()) {
                    group_name = resultSet2.getString("group_name");
                    group_portrait = resultSet2.getString("group_portrait");
                }

                Vector<GMItemView> views = new Vector<>();
                for (String uuid : uids) {
                    String sql4 = "select nickname, portrait from `user` where user_id = ?";
                    ResultSet resultSet4 = database.execResult(sql4, uuid);
                    String memberName = null;
                    String memberPortrait = null;
                    if (resultSet4.next()) {
                        memberName = resultSet4.getString("nickname");
                        memberPortrait = resultSet4.getString("portrait");
                    }
                    if (memberName != null) {
                        GMItemView view = new GMItemView(memberName, memberPortrait);
                        views.add(view);
                    }
                }

                resultSet2.close();
                if (group_name != null) {
                    MsgListItemView itemView = new MsgListItemView(group_name, "", MsgListItemView.TYPE_GROUP);
                    itemView.setHeadPortrait(group_portrait);
                    itemView.setOnlineState(1);
                    gListItemViews.add(itemView);
                    gListView.getItems().add(gListItemViews.get(gListItemViews.size() - 1).getPane());

                    Vector<ChatListItemView> vector = new Vector<>();
                    gMsgListItemMap.put(group_name, vector);

                    groupMemberMap.put(group_name, views);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    public void createNewGroup(String groupName, String groupPortrait, List<String> uids) {
        System.out.println("创建群聊成功");
        Vector<GMItemView> views = new Vector<>();
        try {
            for (String uuid : uids) {
                String sql4 = "select nickname, portrait from `user` where user_id = ?";
                ResultSet resultSet4 = database.execResult(sql4, uuid);
                String memberName = null;
                String memberPortrait = null;
                if (resultSet4.next()) {
                    memberName = resultSet4.getString("nickname");
                    memberPortrait = resultSet4.getString("portrait");
                }
                if (memberName != null) {
                    GMItemView view = new GMItemView(memberName, memberPortrait);
                    views.add(view);
                }
            }
            MsgListItemView itemView = new MsgListItemView(groupName, "", MsgListItemView.TYPE_GROUP);
            itemView.setHeadPortrait(groupPortrait);
            itemView.setOnlineState(1);
            gListItemViews.add(itemView);
            gListView.getItems().add(gListItemViews.get(gListItemViews.size() - 1).getPane());

            Vector<ChatListItemView> vector = new Vector<>();
            gMsgListItemMap.put(groupName, vector);
            groupMemberMap.put(groupName, views);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getId() {
        return id;
    }

    public Database getDatabase() {
        return database;
    }

    public String getYourNickname() {
        return your_nickname;
    }

    public String getYourAccount() {
        return your_account;
    }

    public Map<String, Vector<ChatListItemView>> getfMsgListItemMap() {
        return fMsgListItemMap;
    }
}
